package com.help10000.rms.common

import android.content.res.AssetFileDescriptor
import android.media.AudioManager
import android.media.MediaPlayer

enum class PlayerState {
    /**
     * 准备中
     */
    PREPARING,

    /**
     * 准备完成
     */
    PREPARED,

    /**
     * 播放中
     */
    PLAYING,

    /**
     * 暂停
     */
    PAUSE,

    /**
     * 播放完成
     */
    FINISH,

    /**
     * 发生错误
     */
    ERROR
}

class VoicePlayer {
    /**
     * 播放状态通知
     */
    interface PlayStateListener {
        fun onNotify(state: PlayerState)
    }

    var mediaPlayer = MediaPlayer();

    init {
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnPreparedListener {
            playStateListener?.onNotify(PlayerState.PREPARED)
            mediaPlayer.start()
            playStateListener?.onNotify(PlayerState.PLAYING)
        }
        mediaPlayer.setOnCompletionListener {
            playStateListener?.onNotify(PlayerState.FINISH)
        }
        mediaPlayer.setOnErrorListener { mp, what, extra ->
            playStateListener?.onNotify(PlayerState.ERROR)
            true
        }
    }

    var playStateListener: PlayStateListener? = null

    /**
     * 设置播放监听
     */
    fun setStateListener(listener: PlayStateListener) {
        this.playStateListener = listener
    }

    /**
     * 播放网络地址
     */
    fun play(url: String) {
        try {
            mediaPlayer.stop()
            mediaPlayer.reset()
            mediaPlayer.setDataSource(url)
            mediaPlayer.prepareAsync()
            playStateListener?.onNotify(PlayerState.PREPARING)

        } catch (e: Exception) {
            e.printStackTrace()
            playStateListener?.onNotify(PlayerState.ERROR)
            //   ToastUtil.show("播放发生错误")
        }

    }

    fun play(fileDescriptor: AssetFileDescriptor) {
        try {
            mediaPlayer.stop()
            mediaPlayer.reset()
            mediaPlayer.setDataSource(
                fileDescriptor.fileDescriptor,
                fileDescriptor.startOffset,
                fileDescriptor.length
            )
            mediaPlayer.prepareAsync()
        } catch (e: Exception) {
            playStateListener?.onNotify(PlayerState.ERROR)
            // ToastUtil.show("播放发生错误")
        }

    }


}